<script setup>
import { ref } from 'vue'
import { Plus, Upload } from '@element-plus/icons-vue'
import pageContainer from '@/components/pageContainer.vue'
import { useUserStore } from '@/stores'
import { userUploadAvatarService } from '@/api/user'

// 基于 store 数据，初始化 imageUrl 的初始值
const userStore = useUserStore()
const imageUrl = ref(userStore.user.user_pic)

const uploadRef = ref()

const onSelectFile = (uploadFile) => {
  // imageUrl.value = URL.createObjectURL(uploadFile.raw)

  // 基于 FileReader 读取图片做预览
  const reader = new FileReader()
  reader.readAsDataURL(uploadFile.raw)

  reader.onload = () =>{
    // 这样存储的是 base64 格式的
    imageUrl.value = reader.result
  }
}

const onUpdataAvatar = async () =>{
  // 发送请求更新图像
  await userUploadAvatarService(imageUrl.value)
  // userStore 重新渲染
  await userStore.getUser()
  // 用户提示
  ElMessage.success('更新成功！')
}

</script>
<template>
  <page-container title="更换头像">
    <el-upload ref="uploadRef" :on-change="onSelectFile" class="avatar-uploader" :show-file-list="false" :auto-upload="false">
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
  <el-button @click="uploadRef.$el.querySelector('input').click()" type="primary" :icon="Plus">选择图片</el-button>
  <el-button @click="onUpdataAvatar" type="success" :icon="Upload">上传图像</el-button>
  </page-container>
</template>

<style lang="scss" scoped>
.avatar-uploader{
  :deep(){
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.el-button{
  margin-top: 20px;
}
</style>